/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package es.aurea.presentation.utils;

import es.aurea.interfaces.AcountingRemote;
import es.aurea.interfaces.SecurityRemote;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author zarius
 */
public class EJBLocator {

    private InitialContext ic;
    private Map cache;
    private static EJBLocator me;

    static {
        try {
            me = new EJBLocator();
        } catch (NamingException se) {
            throw new RuntimeException(se);
        }
    }

    private EJBLocator() throws NamingException {
        ic = new InitialContext();
        cache = Collections.synchronizedMap(new HashMap());
    }

    public static EJBLocator getInstance() {
        return me;
    }

    private Object lookup(String jndiName) throws NamingException {
            Object cachedObj = cache.get(jndiName);
            if (cachedObj == null) {
                cachedObj = ic.lookup(jndiName);
                cache.put(jndiName, cachedObj);
            }
            return cachedObj;
        }

    public SecurityRemote getSecurityBean() {
        try {
            return (SecurityRemote) lookup("java:comp/env/SecurityBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "####> EJBLocator error 100: Can not fint the class es.aurea.interfaces.SecurityRemote.");
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "####> Maybe you have not deploy the EJB project?", ne);
            throw new RuntimeException(ne);
        }
    }


    public AcountingRemote getAcountingBean() {
        try {
            return (AcountingRemote) lookup("java:comp/env/AcountingBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "####> EJBLocator error 100: Can not fint the class es.aurea.interfaces.AcountingRemote.");
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "####> Maybe you have not deploy the EJB project?", ne);
            throw new RuntimeException(ne);
        }
    }
}
